import * as allIcon from '@element-plus/icons-vue'
import { ElIcon } from 'element-plus'
import { Component, defineComponent, h, resolveComponent } from 'vue'

const context = Object.keys(import.meta.glob(['@/assets/icons/*.svg'])).map((path) =>
  path.split('/')[path.split('/').length - 1].slice(0, -4),
)
/** 区分是element图标还是自己的svg图标 */
export function useDiscMinSvg(iconName: string, size?: string | number) {
  type Obj = {
    type?: 'el' | 'svg'
    name?: string
    component?: Component
  }
  const obj: Obj = {}
  const SvgIcon = resolveComponent('SvgIcon')
  if (Object.keys(allIcon).includes(iconName)) {
    obj.type = 'el'
    obj.name = iconName
    const ElIconCom = resolveComponent(iconName) as Component
    obj.component = defineComponent({
      render() {
        return h(ElIcon, { size: handleSize(size) }, () => [h(ElIconCom)])
      },
    })
  } else if (context.includes(iconName)) {
    obj.type = 'svg'
    obj.name = iconName
    obj.component = defineComponent({
      render() {
        return h(SvgIcon, { name: iconName, size: handleSize(size) })
      },
    })
  } else {
    throw new Error(`没有名称为${iconName}的icon`)
  }
  return obj
}
function handleSize(size: string | number = 16) {
  if (typeof size === 'string') {
    if (size === 'large') {
      return 18
    } else if (size === 'small') {
      return 14
    } else {
      return 16
    }
  } else {
    return size
  }
}
